#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

static const uint16_t default_port = 8888;
static std::string default_ip = "127.0.0.1";

class Client
{
public:
    Client(std::string& ip = default_ip, const uint16_t& port = default_port)
        :_port(port), _ip(ip)
    {}

    ~Client()
    {
        if(_sockfd > -1)
        {
            close(_sockfd);
        }
    }

    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            std::cout << "Socket failed" << std::endl;
        }
    }

    void Start()
    {
        struct sockaddr_in sock_sever;
        memset(&sock_sever, 0, sizeof(sock_sever));
        sock_sever.sin_family = AF_INET;
        sock_sever.sin_port = htons(_port);
        sock_sever.sin_addr.s_addr = inet_addr(_ip.c_str());

        std::string meassage;
        char buffer[1024];
        while (true)
        {
            std::cout << "Pleas enter:";
            getline(std::cin, meassage);
            int n = sendto(_sockfd, meassage.c_str(), meassage.size(), 0, (const sockaddr*)&sock_sever, sizeof(sock_sever));
            if(n > 0)
            {
                struct sockaddr_in temp;
                memset(&temp, 0, sizeof(temp));
                socklen_t len = sizeof(temp);

                ssize_t m = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (sockaddr*)&temp, &len);
                if(m > 0)
                {
                    buffer[m] = 0;
                    std::cout << buffer << std::endl;
                }
                else
                {
                    std::cout << "Recvfrom failed" << std::endl;
                    continue;
                }
            }
            else
            {
                std::cout << "Sendto failed" << std::endl;
                continue;
            }
        }
        
    }

private:
    int _sockfd;
    uint16_t _port;
    std::string _ip;
};